package com.nuaa.qianru.run;

import org.apache.commons.math3.stat.regression.RegressionResults;
import org.apache.commons.math3.stat.regression.SimpleRegression;

import java.util.ArrayList;
import java.util.List;

public class Waring {
    public static void main(String[] args) {

    }
    public static double[][] linearScatters() {
        List<double[]> data = new ArrayList<>();
        for (double x = 0; x <= 10; x += 0.1) {
            double y = 1.5 * x + 0.5;
            y += Math.random() * 4 - 2; // 随机数
            double[] xy = {x, y};
            data.add(xy);
        }
        return data.stream().toArray(double[][]::new);
    }
    public static double[] linearFit(Double[] data) {
        SimpleRegression regression = new SimpleRegression();
        double res[]=new double[2];
        int n=data.length;
        double [][]datas=new double[n][2];
        for(int i=0;i<n;i++){
            datas[i][0]=i+1;
            datas[i][1]=data[i];
        }
        regression.addData(datas); // 数据集
        /*
         * RegressionResults 中是拟合的结果
         * 其中重要的几个参数如下：
         *   parameters:
         *      0: b
         *      1: k
         *   globalFitInfo
         *      0: 平方误差之和, SSE
         *      1: 平方和, SST
         *      2: R 平方, RSQ
         *      3: 均方误差, MSE
         *      4: 调整后的 R 平方, adjRSQ
         *
         * */
        RegressionResults results = regression.regress();
        double b = results.getParameterEstimate(0);
        double k = results.getParameterEstimate(1);
        double r2 = results.getRSquared();
        res[0]=b;
        res[1]=k;


        StringBuilder func = new StringBuilder();
        func.append("f(x) =");
        func.append(b >= 0 ? " " : " - ");
        func.append(Math.abs(b));
        func.append(k > 0 ? " + " : " - ");
        func.append(Math.abs(k));
        func.append("x");
        return res;

    }

}
